import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
import 'package:city_pickers/city_pickers.dart';
import 'package:labcloud_app/model/user/user_model.dart';
import 'package:labcloud_app/api/graphql/user_gql.dart';
import 'package:labcloud_app/data/user_address.dart';

class AddAddressPage extends StatefulWidget {
  const AddAddressPage({super.key});

  @override
  State<AddAddressPage> createState() => _AddAddressPageState();
}

class _AddAddressPageState extends State<AddAddressPage> {
  final _formKey = GlobalKey<FormState>();

  // 控制器
  final _nameController = TextEditingController();
  final _phoneController = TextEditingController();
  final _provinceController = TextEditingController();
  final _cityController = TextEditingController();
  final _districtController = TextEditingController();
  final _detailController = TextEditingController();
  final _tagController = TextEditingController();

  bool _isDefault = false;
  Result? _selectedResult; // 保存选择的地区结果
  bool _isSaving = false; // 添加保存状态

  @override
  void dispose() {
    // 释放控制器资源
    _nameController.dispose();
    _phoneController.dispose();
    _provinceController.dispose();
    _cityController.dispose();
    _districtController.dispose();
    _detailController.dispose();
    _tagController.dispose();
    super.dispose();
  }

  // 保存地址
  void _saveAddress() async {
    if (_formKey.currentState!.validate()) {
      setState(() {
        _isSaving = true;
      });
      
      try {
        final userModel = Provider.of<UserModel>(context, listen: false);
        final client = GraphQLProvider.of(context).value;

        if (!userModel.isLoggedIn) {
          if (mounted) {
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(content: Text('用户未登录')),
            );
          }
          return;
        }

        // 使用GraphQL添加地址
        final result = await client.mutate(
          MutationOptions(
            document: gql(UserGQL.fetchAddUserAddress),
            variables: {
              'recipientName': _nameController.text,
              'phone': _phoneController.text,
              'province': _provinceController.text,
              'city': _cityController.text,
              'district': _districtController.text,
              'detail': _detailController.text,
              'tag': _tagController.text.isNotEmpty ? _tagController.text : '家',
              'isDefault': _isDefault,
            },
          ),
        );

        if (result.hasException) {
          if (mounted) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(content: Text('地址添加失败: ${result.exception.toString()}')),
            );
          }
        } else {
          // 显示成功消息
          if (mounted) {
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(content: Text('地址添加成功')),
            );

            // 返回结果给上一个页面
            Navigator.pop(context, true);
          }
        }
      } catch (e) {
        // 显示错误消息
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text('地址添加失败: $e')),
          );
        }
      } finally {
        if (mounted) {
          setState(() {
            _isSaving = false;
          });
        }
      }
    }
  }

  // 显示地区选择器
  void _showCityPicker() async {
    Result? result = await CityPickers.showCityPicker(
      context: context,
      // 如果已有选择的地区，可以设置默认值
      // locationCode: _selectedResult?.areaId ?? _selectedResult?.cityId ?? _selectedResult?.provinceId,
      height: 300,
      showType: ShowType.pca, // 省市区三级选择
      cancelWidget: const Text(
        '取消',
        style: TextStyle(
          color: Colors.grey,
          fontSize: 16,
        ),
      ),
      confirmWidget: const Text(
        '确定',
        style: TextStyle(
          color: Colors.blue,
          fontSize: 16,
        ),
      ),
    );

    if (result != null) {
      setState(() {
        _selectedResult = result;
        _provinceController.text = result.provinceName ?? '';
        _cityController.text = result.cityName ?? '';
        _districtController.text = result.areaName ?? '';
      });
    }
  }

  // 清除地区选择
  void _clearCitySelection() {
    setState(() {
      _selectedResult = null;
      _provinceController.clear();
      _cityController.clear();
      _districtController.clear();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('新增地址'),
      ),
      body: Form(
        key: _formKey,
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text(
                '收货人',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 8),
              TextFormField(
                controller: _nameController,
                decoration: const InputDecoration(
                  hintText: '请输入收货人姓名',
                  border: OutlineInputBorder(),
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入收货人姓名';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),

              const Text(
                '手机号码',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 8),
              TextFormField(
                controller: _phoneController,
                decoration: const InputDecoration(
                  hintText: '请输入手机号码',
                  border: OutlineInputBorder(),
                ),
                keyboardType: TextInputType.phone,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入手机号码';
                  }
                  // 简单的手机号验证
                  if (value.length != 11 || !RegExp(r'^1[3-9]\d{9}$').hasMatch(value)) {
                    return '请输入正确的手机号码';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),

              const Text(
                '所在地区',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 8),
              GestureDetector(
                onTap: _showCityPicker,
                child: AbsorbPointer(
                  child: Container(
                    padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 16),
                    decoration: BoxDecoration(
                      border: Border.all(color: Colors.grey),
                      borderRadius: BorderRadius.circular(4),
                    ),
                    child: Row(
                      children: [
                        Expanded(
                          child: Text(
                            _provinceController.text.isEmpty
                                ? '请选择省/市/区'
                                : '${_provinceController.text} ${_cityController.text} ${_districtController.text}',
                            style: TextStyle(
                              color: _provinceController.text.isEmpty
                                  ? Colors.grey
                                  : Colors.black,
                            ),
                          ),
                        ),
                        if (_provinceController.text.isNotEmpty)
                          IconButton(
                            icon: const Icon(Icons.close, size: 20, color: Colors.grey),
                            onPressed: _clearCitySelection,
                          )
                        else
                          const Icon(
                            Icons.arrow_drop_down,
                            color: Colors.grey,
                          ),
                      ],
                    ),
                  ),
                ),
              ),
              const SizedBox(height: 16),

              const Text(
                '详细地址',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 8),
              TextFormField(
                controller: _detailController,
                decoration: const InputDecoration(
                  hintText: '请输入详细地址，如道路、门牌号、小区、楼栋号、单元等信息',
                  border: OutlineInputBorder(),
                ),
                maxLines: 3,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入详细地址';
                  }
                  return null;
                },
              ),
              const SizedBox(height: 16),

              const Text(
                '标签',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(height: 8),
              TextFormField(
                controller: _tagController,
                decoration: const InputDecoration(
                  hintText: '请输入标签，如：家、公司等',
                  border: OutlineInputBorder(),
                ),
              ),
              const SizedBox(height: 16),

              // 设为默认地址
              Row(
                children: [
                  Checkbox(
                    value: _isDefault,
                    onChanged: (value) {
                      setState(() {
                        _isDefault = value ?? false;
                      });
                    },
                  ),
                  const Text('设为默认地址'),
                ],
              ),

              const SizedBox(height: 32),

              // 保存按钮
              SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  onPressed: _isSaving ? null : _saveAddress,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.blue,
                    foregroundColor: Colors.white,
                    padding: const EdgeInsets.symmetric(vertical: 15),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  child: _isSaving
                      ? const SizedBox(
                          width: 20,
                          height: 20,
                          child: CircularProgressIndicator(
                            valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                            strokeWidth: 2,
                          ),
                        )
                      : const Text(
                          '保存地址',
                          style: TextStyle(
                            fontSize: 16,
                          ),
                        ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}